﻿using System.Linq;
using NpCrm.DataAccess.Contracts;
using NpCrm.DataAccess.Core;
using NpCrm.Domain;

namespace NpCrm.DataAccess.Repositories
{
    public class ContactRepository : RepositoryBase<Contact, int>, IContactRepository
    {

        public override void Add(Contact entity)
        {
            entity = NormalizePhoneNumbers(entity);
            base.Add(entity);
        }

        public IQueryable<Contact> GetByName(string lastName)
        {
            return Query(c => c.LastName.ToLower().IndexOf(lastName.ToLower()) > -1);
        }

        public IQueryable<Contact> GetByName(string lastName, string firstName)
        {
            return
                Query(
                    c =>
                    c.LastName.ToLower().IndexOf(lastName.ToLower()) > -1 &&
                    c.FirstName.ToLower().IndexOf(firstName.ToLower()) > -1);
        }

        public IQueryable<Contact> GetByTaxId(string taxId)
        {
            return Query(c => c.TaxIdNumber.ToLower().IndexOf(taxId.ToLower()) > -1);
        }

        public IQueryable<Contact> GetByPhone(string phoneNo)
        {
            phoneNo = new string(phoneNo.Where(n => char.IsDigit(n)).ToArray());
            return
                Query(
                    c =>
                    c.HomePhone.IndexOf(phoneNo) > -1 || c.DaytimePhone.IndexOf(phoneNo) > -1 ||
                    c.MobilePhone.IndexOf(phoneNo) > -1);
        }

        public IQueryable<Contact> GetByEmail(string emailAddress)
        {
            return
                Query(
                    c =>
                    c.PrimaryEmail.ToLower().IndexOf(emailAddress.ToLower()) > -1 ||
                    c.SecondaryEmail.ToLower().IndexOf(emailAddress.ToLower()) > -1);
        }

        private Contact NormalizePhoneNumbers(Contact contact)
        {
            contact.DaytimePhone = new string(contact.DaytimePhone.Where(c => char.IsDigit(c)).ToArray());
            contact.HomePhone = new string(contact.HomePhone.Where(c => char.IsDigit(c)).ToArray());
            contact.MobilePhone = new string(contact.MobilePhone.Where(c => char.IsDigit(c)).ToArray());
            return contact;
        }

    }
}
